package com.yhy.common.service;

import com.yhy.common.exception.CustomRuntimeException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;

public class MyJdbcTemplate extends JdbcTemplate {
    private PlatformTransactionManager platformTransactionManager;
    private DefaultTransactionDefinition transactionDefinition;
    private ThreadLocal<TransactionStatus> transcationStatus = new ThreadLocal<TransactionStatus>();

    public MyJdbcTemplate() {
        super();
    }

    public MyJdbcTemplate(DataSource dataSource) {
        super(dataSource);
    }

    public void beginTranstaion() {
        TransactionStatus tmp = platformTransactionManager.getTransaction(transactionDefinition);
        transcationStatus.set(tmp);
    }

    public void commit() {
        TransactionStatus tmp = transcationStatus.get();
        if (tmp == null) {
            throw new CustomRuntimeException("no transcation");
        }
        platformTransactionManager.commit(tmp);
        transcationStatus.remove();
    }

    public void rollback() {
        TransactionStatus tmp = transcationStatus.get();
        if (tmp == null) {
            throw new CustomRuntimeException("no transcation");
        }
        platformTransactionManager.rollback(tmp);
        transcationStatus.remove();
    }

    @Override
    public void afterPropertiesSet() {
        super.afterPropertiesSet();
        transactionDefinition = new DefaultTransactionDefinition();
        transactionDefinition.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
        transactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        platformTransactionManager = new DataSourceTransactionManager(getDataSource());
    }

}
